package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.execption.XueChengPlusException;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessHistoryMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.MediaProcessHistory;
import com.xuecheng.media.service.MediaProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 *  MediaProcessService的实现类
 * @author XiaoBanGe
 * @since 2023-03-27
 */
@Service
@Slf4j
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements MediaProcessService {



    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MediaProcessHistoryMapper mediaProcessHistoryMapper;

    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    /**
     *  获取处理文件任务
     * @param shardTotal 任务总数
     * @param shardIndex 分片序号
     * @param count 获取记录数
     * @return
     */
    @Override
    public List<MediaProcess> getMediaProcessList(int shardTotal, int shardIndex, int count) {
        return mediaProcessMapper.getMediaProcessList(shardTotal , shardIndex , count);
    }

    /**
     *
     * @param ID 任务ID
     * @return 返回开启任务结果，成功返回：true  失败返回：false
     */
    @Override
    public boolean StartTask(long ID) {
        int startTask = mediaProcessMapper.startTask(ID);
        return startTask <= 0 ? false:true;//失败返回false  成功返回true
    }


    /**
     *  保存任务处理结果
     * @param taskID 任务ID
     * @param status 任务状态
     * @param fileID 文件ID
     * @param Url 处理成功后的文件的URL
     * @param errorMsg 错误信息
     */
    @Transactional
    @Override
    public void SlaveTaskResult(long taskID , String status , String fileID , String Url , String errorMsg) {
        //条件：文件ID
        LambdaQueryWrapper<MediaProcess> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MediaProcess::getId , taskID);
        MediaProcess mediaProcess = mediaProcessMapper.selectById(wrapper);

        if (mediaProcess == null){
            //如果查询不到数据说明文件不存在，或者文件已经被处理
            return;
        }

        //判断任务处理成功  '状态,1:未处理，2：处理成功  3处理失败   4:处理中'
        if (status.equals("3")) {
            //处理失败
            MediaProcess UpdateFailMediaProcess = new MediaProcess();
            UpdateFailMediaProcess.setStatus("3");
            UpdateFailMediaProcess.setErrormsg(errorMsg);
            UpdateFailMediaProcess.setFailCount(mediaProcess.getFailCount() + 1);
            int update = mediaProcessMapper.update(UpdateFailMediaProcess, wrapper);
            if (update <= 0){
                //修改失败抛出异常，让数据回滚
                log.info("修改文件处理状态失败:文件ID{},失败原因{}",fileID,errorMsg);
                throw new XueChengPlusException("修改文件处理状态失败");
            }
            return;
        }

        //处理成功
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess , mediaProcessHistory);
        mediaProcessHistory.setStatus("2");
        mediaProcessHistory.setFinishDate(LocalDateTime.now());
        mediaProcessHistory.setUrl(Url);
        //向文件处理成功的数据表添加记录
        int insert = mediaProcessHistoryMapper.insert(mediaProcessHistory);
        if (insert <= 0){
            //添加失败抛出异常，让数据回滚
            log.info("向历史数据库添加失败:文件ID{},处理成功后的URL{}",fileID , Url);
            throw new XueChengPlusException("文件处理成功，向历史数据库添加失败");
        }

        //删除待处理任务表的记录
        int delete = mediaProcessMapper.delete(wrapper);
        if (delete <= 0){
            //删除失败抛出异常，让数据回滚
            log.info("删除任务表已处理任务失败:文件ID{},处理成功后的URL{}",fileID , Url);
            throw new XueChengPlusException("文件处理成功，删除任务表已处理任务失败");
        }

        //更新文件信息表的URL地址，修改成处理好的文件URL
        LambdaQueryWrapper<MediaFiles> filesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        filesLambdaQueryWrapper.eq(MediaFiles::getFileId , fileID);
        MediaFiles mediaFiles = new MediaFiles();
        mediaFiles.setUrl(Url);
        int mediaFilesUpdate = mediaFilesMapper.update(mediaFiles, filesLambdaQueryWrapper);
        if (mediaFilesUpdate <= 0){
            //修改失败抛出异常，让数据回滚
            log.info("修改文件处理状态失败:文件ID{},失败原因{}",fileID,errorMsg);
            throw new XueChengPlusException("修改文件处理状态失败");
        }
    }
}
